<template>
  <div class="login">
    <img src="~@/assets/logo.png" alt="" class="logo">

    <div class="ipt">
        <input type="text" v-model="uacc" placeholder="请输入用户名(2-16位，只允许出现字母或数字)">
    </div>
    <div class="ipt">
        <input type="password" v-model="upwd" placeholder="请输入密码(8-16位，只允许出现字母或数字)">
    </div>

    <div class="btn" @click="login">登录</div>
  </div>
</template>
    
<script lang="ts" setup>
import { ref, inject } from "vue";
import { postLogin } from '@/api/index'
import { useRouter } from 'vue-router'

const router = useRouter()
const {setTitle, setIsMessage} = inject('nav')

setTitle('登录')

const uacc = ref('')
const upwd = ref('')
const login = () => {
    if(!uacc.value || !upwd.value) {
        alert('请输入用户名和密码')
        return
    }
    if (uacc.value.length < 2 || uacc.value.length > 16) {
        alert('用户名长度为2-16位')
        return
    }
    if (upwd.value.length < 8 || upwd.value.length > 16) {
        alert('密码长度为8-16位')
        return
    }
    // 登录
    postLogin({
        uacc: uacc.value,
        upwd: upwd.value
    }).then(res => {
        if(res.data.code === 200) {
            let user = res.data.data
            localStorage.clear()
            localStorage.setItem('user', JSON.stringify(user))
            router.push({path: '/'})
            setIsMessage('登录成功', true)
        } else {
            localStorage.clear()
            setIsMessage('登录失败，请稍后再试！', false)
        }
    }).catch(() => {
        localStorage.clear()
        setIsMessage('登录失败，请稍后再试！', false)
    })
}

</script>
    
<style lang="less" scoped>
.login {
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 0 2vw;
    overflow: hidden;

    .logo {
        width: 50vw;
        display: block;
        margin: 0 auto;
    }

    .ipt {
        height: 10vw;
        margin-bottom: 10vw;
        border-bottom: 2px solid #12d2ec;

        input {
            border: 0;
            outline: 0;
            height: 100%;
            width: 100%;
            display: block;
            background-color: transparent;
            text-align: center;
            font-size: 16px;
        }
    }

    .btn {
        width: 100%;
        height: 12vw;
        background-color: #12d2ec;
        color: #fff;
        text-align: center;
        line-height: 12vw;
        font-weight: 900;
        border-radius: 4px;
    }
}
</style>